import { createRouter, createWebHashHistory } from 'vue-router';
import { useMemuStore } from '@/store/modules/memu';
import { removeToken } from '@/utils/auth';
import routes from './route';
import handlePermission from './permission';

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach(async (to, from, next) => {
  const store = useMemuStore();
  const route = handlePermission(to, from, next);
  if (typeof route === 'object' && route.path === '/login') {
    next(route);
    return;
  }
  if (to.path.startsWith('/login') && route === true) {
    next();
    return;
  }
  if (!store.memuList?.length) {
    try {
      await store.getMemuList();
    } catch {
      removeToken();
      next({ path: '/login' });
      return;
    }
  }
  if (!store.memuList.some((e) => e.path.startsWith('/demo/warehouse'))) {
    next({ path: '/login' });
    return;
  }
  next(route);
});

export default router;
